<template>
  <div class="purchase-detail-wrap">
    <div class="header flex-c-sb">
      <a-space>
        <p>采购交货单详情</p>
        <span style="font-weight: bold">{{ purchaseDetail.billNo }}</span>
        <a-tag color="arcoblue" size="small" bordered>{{ statusMap[purchaseDetail.status] }}</a-tag>
      </a-space>
      <div class="flex-c-c handle-btn-w">
        <a-space>
          <a-button class="gray-outline" size="medium" @click="closePage">关闭</a-button>
          <a-button v-if="purchaseDetail.status == 30 && $authPass('procurement.delivery.edit')" type="primary" size="medium" @click="showEditDeliveryOrder = true">编辑</a-button>
          <a-button v-if="purchaseDetail.status == 30 && $authPass('procurement.delivery.sign')" type="primary" size="medium" @click="showHandleDeliveryOrder = true">签收交货单</a-button>
          <a-button v-if="purchaseDetail.status == 30 && $authPass('procurement.delivery.delete')" class="gray-outline" size="medium" @click="submitCancellation">作废</a-button>
          <a-button v-if="purchaseDetail.status == 40 && $authPass('procurement.delivery.receipt')" type="primary" size="medium" @click="showHandleWarehousing = true">确认入库</a-button>
          <a-button v-if="purchaseDetail.status == 40 && $authPass('procurement.delivery.revoke')" class="gray-outline" size="medium" @click="submitRevocation">撤回待处理</a-button>
        </a-space>
      </div>
    </div>
    <div class="base-w">
      <div class="base-con">
        <a-row>
          <a-col :span="6">
            <p>
              <span class="label">创建人：</span>
              <span>{{ purchaseDetail.createUname }}</span>
            </p>
          </a-col>
          <a-col :span="6">
            <p>
              <span class="label">创建时间：</span>
              <span>{{ $setTime(purchaseDetail.gmtCreate, 'YYYY/MM/DD HH:mm') }}</span>
            </p>
          </a-col>
          <a-col :span="6">
            <p>
              <span class="label">签收人：</span>
              <span>{{ purchaseDetail.signUname }}</span>
            </p>
          </a-col>
          <a-col :span="6">
            <p>
              <span class="label">签收时间：</span>
              <span>{{ $setTime(purchaseDetail.gmtSign, 'YYYY/MM/DD HH:mm') }}</span>
            </p>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="6">
            <div class="flex">
              <span class="label">目的仓库：</span>
              <span>{{ purchaseDetail.warehouseName }}({{ purchaseDetail.warehouseCode }})</span>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="flex">
              <span class="label">供应商：</span>
              <span>{{ purchaseDetail.supplierName }}</span>
            </div>
          </a-col>
          <a-col :span="6">
            <p>
              <span class="label">交货日期：</span>
              <span>{{ $setTime(purchaseDetail.gmtDelivery, 'YYYY/MM/DD HH:mm') }}</span>
            </p>
          </a-col>
          <a-col :span="6">
            <div class="flex">
              <span class="label">备注：</span>
              <a-popover>
                <template #content>
                  <p style="width: 400px">{{ purchaseDetail.remark }}</p>
                </template>
                <p class="text-limit" style="flex: 1">{{ purchaseDetail.remark }}</p>
              </a-popover>
              <a-popconfirm v-if="purchaseDetail.status == 30" @popup-visible-change="popupChange($event, purchaseDetail.remark)" @ok="updateRemark">
                <template #content>
                  <a-textarea v-model="editVal" style="width: 260px; height: 150px" placeholder="请输入备注" allow-clear />
                </template>
                <icon-edit style="margin-top: 2px" class="highlight cursor" />
              </a-popconfirm>
            </div>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="6">
            <p>
              <span class="label">物流方式：</span>
              <span>{{ purchaseDetail.logisticType === 1 ? '线下' : '快递' }}</span>
            </p>
          </a-col>
          <a-col :span="6">
            <p>
              <span class="label">物流跟踪号：</span>
              <span v-if="purchaseDetail.logisticName">{{ purchaseDetail.logisticName }}/</span>
              <span>{{ purchaseDetail.logisticsTrackNumber }}</span>
            </p>
          </a-col>
          <a-col :span="12">
            <div class="flex" v-if="purchaseDetail.status == 30">
              <span class="label">附件：</span>
              <ul style="margin-right: 10px">
                <li v-for="(url, i) in purchaseDetail.attachment" style="margin-bottom: 4px" :key="i">
                  <a-tag color="arcoblue" closable @close="closedAttachment(i)">{{ url }}</a-tag>
                </li>
              </ul>
              <a-upload action="/" :custom-request="uplaodFile" :show-file-list="false">
                <template #upload-button>
                  <a-button size="mini" type="outline">
                    <template #icon>
                      <icon-upload />
                    </template>
                    <template #default>上传附件</template>
                  </a-button>
                </template>
              </a-upload>
            </div>
            <div class="flex" v-else>
              <span class="label" style="flex-shrink: 0">附件：</span>
              <ul style="margin-right: 10px" v-if="purchaseDetail.attachment">
                <li v-for="(url, i) in purchaseDetail.attachment" style="margin-bottom: 4px" :key="i">
                  <a-tag color="arcoblue" class="cursor" @click="downloadFile(url)">
                    <span>{{ url }}</span>
                    <icon-to-bottom />
                  </a-tag>
                </li>
              </ul>
              <p v-else>--</p>
            </div>
          </a-col>
        </a-row>
      </div>
    </div>
    <div class="purchase-detail-con">
      <a-tabs v-model:active-key="activeTab">
        <a-tab-pane key="1" title="交货单明细" />
        <a-tab-pane key="2" title="入库明细" />
        <a-tab-pane key="3" title="操作日志" />
      </a-tabs>
      <div class="purchase-detail-order">
        <PurchaseDeliveryItem v-if="activeTab == '1'" :currentData="purchaseDetail" />
        <DeliveryInStorageItem v-if="activeTab == '2'" :currentData="purchaseDetail" />
        <PurchaseLogs v-if="activeTab == '3'" api="findDeliveryLogPage" :currentData="purchaseDetail" />
      </div>
    </div>
  </div>
  <!-- 签收交货单 -->
  <HandleDeliveryOrder v-if="showHandleDeliveryOrder" :isShow="showHandleDeliveryOrder" :currentItem="purchaseDetail" @closed="showHandleDeliveryOrder = false" @success="getPurchaseDetail" />
  <!-- 提交入库单 -->
  <HandleWarehousing v-if="showHandleWarehousing" :isShow="showHandleWarehousing" :currentItem="purchaseDetail" @closed="showHandleWarehousing = false" @success="getPurchaseDetail" />
  <!-- 编辑发货单 -->
  <AddDeliveryOrderSingle v-if="showEditDeliveryOrder" type="edit" :isShow="showEditDeliveryOrder" :currentItem="purchaseDetail" @closed="showEditDeliveryOrder = false" @success="getPurchaseDetail" />
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  import { useRouter, useRoute } from 'vue-router'
  import HandleDeliveryOrder from './components/handleDeliveryOrder.vue'
  import HandleWarehousing from './components/handleWarehousing.vue'
  import PurchaseDeliveryItem from './components/purchaseDeliveryItem.vue'
  import DeliveryInStorageItem from './components/deliveryInStorageItem.vue'
  import { getDeliveryInfo, revokeDeliveryOrder, cancelDeliveryOrder, updateDeliveryOrder } from '@/api/purchase'
  import PurchaseLogs from './components/purchaseLogs.vue'
  import { upload } from '@/api/base'
  import AddDeliveryOrderSingle from './components/addDeliveryOrderSingle.vue'

  onMounted(() => {
    getPurchaseDetail()
  })

  const statusMap = {
    0: '已作废',
    30: '待签收',
    40: '待入库',
    50: '入库中',
    60: '已入库',
  }
  const visitedRouteStore = useVisitedRouteStore()
  const route = useRoute()
  const router = useRouter()
  const showHandleDeliveryOrder = ref(false)
  const showHandleWarehousing = ref(false)
  const purchaseDetail = ref<any>({})
  const activeTab = ref('1')
  const editVal = ref()
  const showEditDeliveryOrder = ref(false)

  // 获取采购交货单详情
  async function getPurchaseDetail() {
    const res: any = await getDeliveryInfo({ id: route.query.id })
    purchaseDetail.value = res?.data || {}
    purchaseDetail.value.attachment = purchaseDetail.value.attachment ? purchaseDetail.value.attachment.split(',') : []
  }

  // 关闭界面
  function closePage() {
    visitedRouteStore.removeVisitedRoute(route)
    router.push('/purchase/purchaseManagement/purchaseDelivery')
  }
  // 作废
  function submitCancellation() {
    Modal.confirm({
      title: '作废',
      content: `请再次确认是否需要作废该加货单？`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await cancelDeliveryOrder({ ids: [purchaseDetail.value.id] })
        if (res) {
          Message.success('作废成功')
          getPurchaseDetail()
        }
      },
    })
  }
  // 撤回待处理
  function submitRevocation() {
    Modal.confirm({
      title: '撤回待处理',
      content: `请再次确认是否需要把该交货单撤回到待处理状态`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await revokeDeliveryOrder({ ids: [purchaseDetail.value.id] })
        if (res) {
          Message.success('撤回草稿箱成功')
          getPurchaseDetail()
        }
      },
    })
  }
  // 直接编辑
  function popupChange(state: boolean, val: any) {
    if (state) {
      editVal.value = val
    }
  }
  // 编辑备注
  async function updateRemark() {
    const res: any = await updateDeliveryOrder({
      id: purchaseDetail.value.id,
      remark: editVal.value,
    })
    if (res) {
      getPurchaseDetail()
    }
  }
  // 上传附件
  const uplaodFile: any = async (options: any) => {
    let { fileItem } = options
    let formData = new FormData()
    formData.append('file', fileItem.file)
    const res: any = await upload(formData)
    if (res?.data?.publicUrl) {
      purchaseDetail.value.attachment.push(res.data.publicUrl)
      updateAttachment()
    }
  }
  // 删除附件
  function closedAttachment(index: number) {
    purchaseDetail.value.attachment.splice(index, 1)
    updateAttachment()
  }
  // 编辑附件
  async function updateAttachment() {
    const res: any = await updateDeliveryOrder({
      id: purchaseDetail.value.id,
      attachment: purchaseDetail.value.attachment?.join(','),
    })
    if (res) {
      getPurchaseDetail()
    }
  }
  //  下载
  function downloadFile(url: string) {
    let _url = url
    if (_url.indexOf('?') > -1) {
      _url += '&response-content-type=application/octet-stream'
    } else {
      _url += '?response-content-type=application/octet-stream'
    }
    let link = document.createElement('a')
    link.href = _url
    link.click()
  }
</script>
<style lang="less" scoped>
  .purchase-detail-wrap {
    height: calc(100vh - @menuHeight);
    display: flex;
    flex-direction: column;
    .header {
      padding: 10px;
      background-color: #fff;
      margin-bottom: 10px;
    }
    .purchase-detail-con {
      flex: 1;
      background-color: #fff;
      margin-top: 10px;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      .purchase-detail-order {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        padding: 10px 20px;
      }
    }
    .base-w {
      background-color: #fff;
      padding: 20px 10px;
      .arco-steps {
        max-width: 1000px;
      }
      .label {
        display: inline-block;
        width: 120px;
        text-align: right;
        flex-shrink: 0;
      }
    }
  }
</style>
